<template>
    <div class="installationPlan">
        <cjcNav title="设置打卡计划" @customRouter="customRouter"></cjcNav>
        <headTime :time="this.$route.params.week" />
        <div class="forenoon" v-if="forenoon">
            <div class="ipList">
                <div class="tilte">设置上午时间段</div>
                <Row class="XQ">
                    <Col span="14">
                    <TimePicker v-if="!disabled.forenoon" v-model="forenoonTime" hide-disabled-options :disabled-minutes="DM" :disabled-hours="DH.forenoon" :editable="false" format="HH:mm" type="timerange" placement="bottom-start" placeholder="不设置"></TimePicker>
                    <TimePicker v-else disabled placeholder="当前时间不可设置"></TimePicker>
                    </Col>

                    <Col span="10">
                    <Select v-if="!disabled.forenoon" v-model="XQ.forenoon" placeholder="校区选择">
                        <Option :value="item.REGION_ID" :key="item.REGION_ID" v-for="item in $store.state.SchoolList">{{item.REGION_NAME}}</Option>
                    </Select>
                    <Select v-else v-model="XQ.forenoon" disabled placeholder="不可设置">
                    </Select>
                    </Col>

                </Row>
                <Row class="address">
                    <Col span=24>
                        <Select v-if="!disabled.forenoon" v-model="address.forenoon" placeholder="请选择地址">
                            <Option :value="item.BUILDING_ID" :key="item.BUILDING_ID" v-for="item in $store.state.BuildingList.forenoon">{{item.BUILDING_NAME}}</Option>
                        </Select>
                        <!-- <Input v-if="!disabled.forenoon" v-model="address.forenoon" placeholder="此处填写详细地址"></Input> -->
                        <Input v-else v-model="address.forenoon" disabled placeholder="不可设置"></Input>
                    </Col>
                </Row>
            </div>
        </div>
        <div class="afternoon" v-if="afternoonArea">
            <div class="ipList">
                <div class="tilte">设置下午时间段</div>
                <Row class="XQ">
                    <Col span="14">
                    <TimePicker v-if="!disabled.afternoon" v-model="afternoonTime" hide-disabled-options :disabled-minutes="DM" :disabled-hours="DH.afternoon" :editable="false" format="HH:mm" type="timerange" placement="bottom-start" placeholder="不设置"></TimePicker>
                    <TimePicker v-else disabled placeholder="当前时间不可设置"></TimePicker>
                    </Col>
                    <Col span="10">
                    <Select v-if="!disabled.afternoon" v-model="XQ.afternoon" placeholder="校区选择">
                        <Option :value="item.REGION_ID" :key="item.REGION_ID" v-for="item in $store.state.SchoolList">{{item.REGION_NAME}}</Option>
                    </Select>
                    <Select v-else v-model="XQ.afternoon" disabled placeholder="不可设置">
                    </Select>
                    </Col>
                </Row>
                <Row class="address">
                    <Col span=24>
                        <Select v-if="!disabled.afternoon" v-model="address.afternoon" placeholder="请选择地址">
                            <Option :value="item.BUILDING_ID" :key="item.BUILDING_ID" v-for="item in $store.state.BuildingList.afternoon">{{item.BUILDING_NAME}}</Option>
                        </Select>
                        <!-- <Input v-if="!disabled.afternoon" v-model="address.afternoon" placeholder="此处填写详细地址"></Input> -->
                        <Input v-else v-model="address.afternoon" disabled placeholder="不可设置"></Input>
                    </Col>
                </Row>
            </div>
        </div>
        <div class="bnt-area">
            <Button type="primary" @click="issue" v-if="$route.params.type === 1" size="large" long>提交</Button>
            <Button type="primary" @click="changePlan" v-if="showBtn" size="large" long>修改</Button>
            <div class="btn-dete" @click="deletePlanJude" v-if="showBtn">删除</div>
        </div>
        <Spin size="large" style="position: fixed" fix v-if="loading"></Spin>
    </div>
</template>

<script>
export default {
    components: {
        cjcNav: () => import('@/components/common/Nav.vue'),
        headTime: () => import('@/components/common/headTime.vue'),
    },
    data() {
        return {
            XQ: {
                forenoon: '01',
                afternoon: '01'
            },
            disabled: {
                forenoon: false,
                afternoon: false
            },
            forenoonTime: [],
            afternoonTime: [],
            address: {
                forenoon: '',
                afternoon: ''
            },
            DM: (function() {
                let tempArray = []
                for (let i = 0; i <= 60; i++) {
                    if (i % 5 !== 0) {
                        tempArray.push(i)
                    }
                }
                return tempArray
            })(),
            DH: {
                forenoon: [],
                afternoon: []
            },
            day: this.$route.params.day.replace(/-/g, '/'),
            loading: false
        }
    },
    computed: {
        afternoonArea() {
            if (this.$route.params.type === 1) {
                if (this.$route.params.planId.afternoon === undefined) {
                    return true
                }
                return false
            } else if (this.$route.params.type === 2) {
                if (this.$route.params.planId.afternoon === undefined) {
                    return false
                }
                return true
            }
        },
        forenoon() {
            if (this.$route.params.type === 1) {
                if (this.$route.params.planId.forenoon === undefined) {
                    return true
                }
                return false
            } else if (this.$route.params.type === 2) {
                if (this.$route.params.planId.forenoon === undefined) {
                    return false
                }
                return true
            }
        },
        showBtn() {
            if (this.$route.params.type === 1) {
                return false
            }
            if (this.$route.params.type === 2 && (this.disabled.forenoon === true && this.disabled.afternoon === true)) {
                return false
            }
            if (this.$route.params.type === 2 && (this.afternoonArea === false && this.disabled.forenoon === true)) {
                return false
            }
            if (this.$route.params.type === 2 && (this.forenoon === false && this.disabled.afternoon === true)) {
                return false
            }
            return true
        }
    },
    watch: {
        async 'XQ.afternoon'() {
            // 设置下午的楼栋
            let BuildingListAfternoon = await this.$store.dispatch('getBuildingList', {
                REGION_ID: this.XQ.afternoon
            })
            this.$store.commit('SET_BuildingList', {result: BuildingListAfternoon.result, type: 2})
        },
        async 'XQ.forenoon'() {
            // 设置上午的楼栋
            let BuildingListForenoon = await this.$store.dispatch('getBuildingList', {
                REGION_ID: this.XQ.forenoon
            })
            this.$store.commit('SET_BuildingList', {result: BuildingListForenoon.result, type: 1})
        }
    },
    methods: {
        customRouter() {
            // 自定义路由
            this.$router.push({
                name: 'installationPlanLIst',
                params: {
                    zc: this.$route.params.zc
                }
            })
        },
        deletePlanJude() {
            if (this.$route.params.planId.forenoon !== undefined && this.$route.params.planId.afternoon !== undefined) {
                this.$store.dispatch('deletePlan', {
                    planId: this.$route.params.planId.forenoon,
                    userId: this.$store.state.userInfo.USER_ID
                }).then(forenoonRes => {
                    this.$store.dispatch('deletePlan', {
                        planId: this.$route.params.planId.afternoon,
                        userId: this.$store.state.userInfo.USER_ID
                    }).then(afternoonRes => {
                        if (forenoonRes.status === 0 && afternoonRes.status === 0) {
                            this.$Message.success('删除成功')
                            this.$router.push({
                                name: 'installationPlanLIst'
                            })
                        } else {
                            if (forenoonRes.status !== 0) {
                                this.$Message.error('上午计划删除失败')
                            }
                            if (afternoonRes.status !== 0) {
                                this.$Message.error('下午计划删除失败')
                            }
                        }
                    })
                })
            } else {
                if (this.$route.params.planId.forenoon !== undefined) {
                    this.$store.dispatch('deletePlan', {
                        planId: this.$route.params.planId.forenoon,
                        userId: this.$store.state.userInfo.USER_ID
                    }).then(res => {
                        if (res.status === 0) {
                            this.$Message.success(res.msg)
                            this.$router.push({
                                name: 'installationPlanLIst'
                            })
                        } else {
                            this.$Message.error('上午计划删除失败')
                        }
                    })
                }
                if (this.$route.params.planId.afternoon !== undefined) {
                    this.$store.dispatch('deletePlan', {
                        planId: this.$route.params.planId.afternoon,
                        userId: this.$store.state.userInfo.USER_ID
                    }).then(res => {
                        if (res.status === 0) {
                            this.$router.push({
                                name: 'installationPlanLIst'
                            })
                        } else {
                            this.$Message.error('下午计划删除失败')
                        }
                    })
                }
            }
        },
        deletePlan(planId) {
            this.$store.dispatch('deletePlan', {
                planId,
                userId: this.$store.state.userInfo.USER_ID
            }).then(res => {
                console.log(res)
                return res.status
            })
        },
        /**
         * 判断该时间段是否可选
         */
        async judgeSetTime(type, day) {
            console.log(day)
            console.log(type)
            return await this.$store.dispatch('checkTime', {
                day,
                type
            })
        },
        /**
         * 判断上下午是否可选
         */
        judegTime(day) {
            this.loading = true
            this.judgeSetTime(0, day).then(res => {
                if (res.data.status === 0) {
                    this.disabled.forenoon = false
                } else {
                    this.disabled.forenoon = true
                }
            })
            this.judgeSetTime(1, day).then(res => {
                this.loading = false
                if (res.data.status === 0) {
                    this.disabled.afternoon = false
                } else {
                    this.disabled.afternoon = true
                }
            })
        },
        /**
         * 设置能够设置的规定时间
        */
        async setTimeList(day) {
            let TimeList = await this.$store.dispatch('getTimeList', {
                day
            })
            this.$store.commit('SET_TimeList', TimeList.data.result)
        },
        /**
         * 设置可选的时间范围
         */
        setSelctTimeScoped(type) {
            let strTime = this.$store.state.TimeList[type].START_TIME.split(':')[0]
            let endTime = this.$store.state.TimeList[type].END_TIME.split(':')[0]
            let tempArray = []
            for (let i = 0; i <= 24; i++) {
                if (i < strTime || i > endTime) {
                    tempArray.push(i)
                }
            }
            return tempArray
        },
        /**
         * 设置校区列表
        */
        async setSchoolList() {
            let SchoolList = await this.$store.dispatch('getSchoolList')
            this.$store.commit('SET_SchoolList', SchoolList.result)
        },
        /**
         * 设置楼栋
        */
        async setBuildingList(xq) {
            // 设置上午的楼栋
            let BuildingListForenoon = await this.$store.dispatch('getBuildingList', {
                REGION_ID: xq.forenoon
            })
            // 设置下午的楼栋
            let BuildingListAfternoon = await this.$store.dispatch('getBuildingList', {
                REGION_ID: xq.afternoon
            })
            this.$store.commit('SET_BuildingList', {result: BuildingListForenoon.result, type: 1})
            this.$store.commit('SET_BuildingList', {result: BuildingListAfternoon.result, type: 2})
        },
        changePlan() {
            let timeStatus = this.judePageTime()
            if (timeStatus === 2) {
                this.$Message.error('设定时间不在规定范围内')
            } else if (timeStatus) {
                if (this.forenoonTime !== undefined) {
                    if (this.forenoonTime.length !== 0) {
                        if (this.address.forenoon === '') {
                            this.$Message.warning('请填写上午地址')
                            return
                        }
                        this.changePlanSetting(0)
                    }
                }
                if (this.afternoonTime !== undefined) {
                    if (this.afternoonTime.length !== 0) {
                        if (this.address.afternoon === '') {
                            this.$Message.warning('请填写下午地址')
                            return
                        }
                        this.changePlanSetting(1)
                    }
                }
                if (this.forenoonTime === undefined && this.afternoonTime === undefined) {
                    this.$Message.warning('当前时间不可设置计划')
                } else if (this.forenoonTime !== undefined || this.afternoonTime !== undefined) {
                    return
                } else if (this.forenoonTime.length === 0 && this.afternoonTime.length === 0) {
                    this.$Message.warning('请选择时间')
                }
            } else {
                this.$Message.error('开始时间与结束时间一样')
            }
        },
        /**
         * 编辑订单
        */
        changePlanSetting(type) {
            let startTime, endTime, userId, address, regionId
            if (type === 0) {
                startTime = this.forenoonTime[0].toTimeString().split(' ')[0]
                endTime = this.forenoonTime[1].toTimeString().split(' ')[0]
                regionId = this.XQ.forenoon
                address = this.address.forenoon
            } else if (type === 1) {
                startTime = this.afternoonTime[0].toTimeString().split(' ')[0]
                endTime = this.afternoonTime[1].toTimeString().split(' ')[0]
                regionId = this.XQ.afternoon
                address = this.address.afternoon
            }
            userId = this.$store.state.userInfo.USER_ID
            // 获取计划ID
            let planId
            if (type === 0) {
                planId = this.$route.params.planId.forenoon
            } else if (type === 1) {
                planId = this.$route.params.planId.afternoon
            }
            this.$store.dispatch('changePlan', {
                plan_id: planId,
                day: this.day,
                type,
                startTime,
                endTime,
                user_id: userId,
                region_id: regionId,
                address
            }).then(res => {
                if (res.data.status === 0) {
                    this.$Message.success(res.data.msg)
                    this.$router.push({
                        name: 'installationPlanLIst',
                        params: {
                            zc: this.$route.params.zc
                        }
                    })
                } else {
                    this.$Message.error(res.data.msg)
                }
            })
        },
        /**
         * 发布订单
         */
        issueSetting(type) {
            let startTime, endTime, userId, address, regionId
            if (type === 0) {
                startTime = this.forenoonTime[0].toTimeString().split(' ')[0]
                endTime = this.forenoonTime[1].toTimeString().split(' ')[0]
                regionId = this.XQ.forenoon
                address = this.address.forenoon
            } else if (type === 1) {
                startTime = this.afternoonTime[0].toTimeString().split(' ')[0]
                endTime = this.afternoonTime[1].toTimeString().split(' ')[0]
                regionId = this.XQ.afternoon
                address = this.address.afternoon
            }
            userId = this.$store.state.userInfo.USER_ID
            this.$store.dispatch('savePlan', {
                day: this.day,
                type,
                startTime,
                endTime,
                user_id: userId,
                region_id: regionId,
                address
            }).then(res => {
                if (res.data.status === 0) {
                    this.$Message.success(res.data.msg)
                    this.$router.push({
                        name: 'installationPlanLIst',
                        params: {
                            zc: this.$route.params.zc
                        }
                    })
                } else {
                    this.$Message.error(res.data.msg)
                }
            })
        },
        judePageTime() {
            // 在同时设置了上午时间段和下午时间段的情况下 返回2则设定时间不在范围内
            if (this.forenoonTime !== undefined && this.afternoonTime !== undefined) {
                if ((this.forenoonTime !== '' && this.forenoonTime.length !== 0) && (this.afternoonTime !== '' && this.afternoonTime.length !== 0)) {
                    let one = this.forenoonTime[0].toTimeString().split(' ')[0]
                    let two = this.forenoonTime[1].toTimeString().split(' ')[0]
                    let three = this.afternoonTime[0].toTimeString().split(' ')[0]
                    let four = this.afternoonTime[1].toTimeString().split(' ')[0]
                    if (this.forenoonTime[1].getTime() - new Date(new Date().toLocaleDateString() + ' ' + this.$store.state.TimeList[0].END_TIME).getTime() > 10000 || this.afternoonTime[1].getTime() - new Date(new Date().toLocaleDateString() + ' ' + this.$store.state.TimeList[1].END_TIME).getTime() > 10000) {
                        return 2
                    } else {
                        if (one === two) {
                            return false
                        } else if (three === four) {
                            return false
                        }
                    }
                } else if (this.forenoonTime !== '' && this.forenoonTime.length !== 0) {
                    let one = this.forenoonTime[0].toTimeString().split(' ')[0]
                    let two = this.forenoonTime[1].toTimeString().split(' ')[0]
                    if (this.forenoonTime[1].getTime() - new Date(new Date().toLocaleDateString() + ' ' + this.$store.state.TimeList[0].END_TIME).getTime() > 10000) {
                        return 2
                    } else {
                        if (one === two) {
                            return false
                        }
                    }
                } else if (this.afternoonTime !== '' && this.afternoonTime.length !== 0) {
                    let three = this.afternoonTime[0].toTimeString().split(' ')[0]
                    let four = this.afternoonTime[1].toTimeString().split(' ')[0]
                    if (this.afternoonTime[1].getTime() - new Date(new Date().toLocaleDateString() + ' ' + this.$store.state.TimeList[1].END_TIME).getTime() > 10000) {
                        return 2
                    } else {
                        if (three === four) {
                            return false
                        }
                    }
                }
                return true
            } else if (this.forenoonTime !== undefined) {
                if (this.forenoonTime !== '' && this.forenoonTime.length !== 0) {
                    let one = this.forenoonTime[0].toTimeString().split(' ')[0]
                    let two = this.forenoonTime[1].toTimeString().split(' ')[0]
                    if (one === two) {
                        return false
                    }
                }
                return true
            } else if (this.afternoonTime !== undefined) {
                if (this.afternoonTime !== '' && this.afternoonTime.length !== 0) {
                    let three = this.afternoonTime[0].toTimeString().split(' ')[0]
                    let four = this.afternoonTime[1].toTimeString().split(' ')[0]
                    if (three === four) {
                        return false
                    }
                }
                return true
            }
        },
        issue() {
            let timeStatus = this.judePageTime()
            if (timeStatus === 2) {
                this.$Message.error('设定时间不在规定范围内')
            } else if (timeStatus) {
                if (this.forenoonTime !== undefined) {
                    if (this.forenoonTime.length !== 0) {
                        if (this.address.forenoon === '') {
                            this.$Message.warning('请填写上午地址')
                            return
                        }
                        this.issueSetting(0)
                    }
                }
                if (this.afternoonTime !== undefined) {
                    if (this.afternoonTime.length !== 0) {
                        if (this.address.afternoon === '') {
                            this.$Message.warning('请填写下午地址')
                            return
                        }
                        this.issueSetting(1)
                    }
                }
                if (this.forenoonTime === undefined && this.afternoonTime === undefined) {
                    this.$Message.warning('当前时间不可设置计划')
                } else if (this.forenoonTime !== undefined || this.afternoonTime !== undefined) {
                    return
                } else if (this.forenoonTime.length === 0 && this.afternoonTime.length === 0) {
                    this.$Message.warning('请选择时间')
                }
            } else {
                this.$Message.error('开始时间与结束时间一样')
            }
        }
    },
    created() {
        const Vm = this
        let day = this.day
        function initData() {
            if (Vm.$route.params.info !== undefined) {
                Vm.XQ = {
                    forenoon: Vm.$route.params.info[0].REGION_ID,
                    afternoon: Vm.$route.params.info[1].REGION_ID,
                }
                if (Vm.$route.params.info[0].ADDRESS !== undefined) {
                    Vm.address.forenoon = Vm.$route.params.info[0].BUILDING_ID
                }
                if (Vm.$route.params.info[1].ADDRESS !== undefined) {
                    Vm.address.afternoon = Vm.$route.params.info[1].BUILDING_ID
                }
                if (Vm.$route.params.info[0].START_TIME !== undefined) {
                    Vm.forenoonTime = [Vm.$route.params.info[0].START_TIME, Vm.$route.params.info[0].END_TIME]
                }
                if (Vm.$route.params.info[1].START_TIME !== undefined) {
                    Vm.afternoonTime = [Vm.$route.params.info[1].START_TIME, Vm.$route.params.info[1].END_TIME]
                }
            }
        }
        async function step() {
            // 判断上午是否可选
            initData()
            // 设置上午和下午楼栋
            Vm.setBuildingList(Vm.XQ)
            Vm.setSchoolList()
            Vm.judegTime(day)
            await Vm.setTimeList(day)
            Vm.DH.forenoon = Vm.setSelctTimeScoped(0)
            Vm.DH.afternoon = Vm.setSelctTimeScoped(1)
        }
        step()
    }
}
</script>

<style lang="less">
.installationPlan {
    .nav {
        box-shadow: none;
    }
    .ipList {
        padding: 0 20px;
        font-size: 14px;
        background-color: #fff;
        .tilte {
            padding: 10px 0;
            color: #8b8b8b;
            border-bottom: 1px solid #f8f8f8;
        }
        .XQ {
            padding-top: 10px;
        }
        .address {
            padding: 15px 0;
        }
        .ivu-time-picker-cells-list ul {
            padding: 0;
        }
        .ivu-time-picker-cells-list {
            overflow-x: hidden;
            overflow-y: scroll;
        }
    }
    .forenoon {}
    .afternoon {
        margin-top: 20px;
    }
    .bnt-area {
        padding: 40px 15px 0;
        text-align: center;
        .btn-dete {
            color: red;
            background-color: #fff;
            margin-top: 20px;
            padding: 6px 15px 7px 15px;
            font-size: 14px;
            border-radius: 4px;
            border-style: solid;
            border-width: 1px;
            border-color: #f4f1f1;
        }
    }
}
</style>
